<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名称" v-model="whereQuery.name"></el-input>
      <el-select style="width: 190px" clearable class="filter-item" v-model="whereQuery.categoryId" filterable placeholder="分类" @change="handleFilter">
        <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id">
        </el-option>
      </el-select>
      <el-select class="filter-item" v-model="whereQuery.tagId" clearable filterable remote placeholder="请输入标签" :remote-method="remoteTagMethod" @change="handleFilter" :loading="tagLoading">
        <el-option v-for="item in tagOptions" :key="item._id" :label="item.name" :value="item._id">
        </el-option>
      </el-select>
      <el-select clearable style="width: 120px" class="filter-item" v-model="whereQuery.status" placeholder="状态" @change="handleFilter">
        <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" v-waves @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" sortable="custom" @sort-change='handleOrder'>
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间" sortable prop="createdAt">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="190px" header-align="center" label="名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" header-align="center" label="当前版本" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.versionInfo" @click="showJsonObject(scope.row.versionInfo)">{{scope.row.versionInfo.versionName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" align="center" label="分类" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.category" @click="showJsonObject(scope.row.category)">{{scope.row.category.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="90" class-name="small-padding">
        <template slot-scope="scope">
          <el-button size="medium" type="text" @click="editAppTag(scope.row)">编辑标签
          </el-button>
        </template>
      </el-table-column>
      <el-table-column min-width="190px" header-align="center" label="包名" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.packageName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" header-align="center" label="厂商" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.vendor" @click="showJsonObject(scope.row.vendor)">{{scope.row.vendor.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" align="center" label="评分" sortable prop="score">
        <template slot-scope="scope">
          <span>{{scope.row.score}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" align="center" label="权重值" sortable prop="weight">
        <template slot-scope="scope">
          <span>{{scope.row.weight}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="下载量" sortable prop="downloads">
        <template slot-scope="scope">
          <span>{{scope.row.downloads}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="浏览量" sortable prop="pageviews">
        <template slot-scope="scope">
          <span>{{scope.row.pageviews}}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="启动次数" sortable prop="opens">
        <template slot-scope="scope">
          <span>{{scope.row.opens}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="190px" header-align="center" label="简介" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.brief}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="190px" header-align="center" label="副标题" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.subtitle}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="210" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status != 1" size="mini" type="primary" @click="handleStatus(scope.row, 1)">发布</el-button>
          <el-button v-else size="mini" type="warning" @click="handleStatus(scope.row, 3)">下架</el-button>
          <el-button size="mini" type="danger" v-bind:disabled="scope.row.status === 1" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="编辑标签" :visible.sync="tagDialogVisible">
      <el-form label-position="right" style='min-width: 500px;' v-loading="tagEditLoading">
        <el-form-item label="标签">
          <el-tag :key="tag._id" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">{{tag.name}}</el-tag>
          <el-select v-if="inputVisible" ref="saveTagInput" style="width: 120px" v-model="inputValue" clearable filterable remote placeholder="输入标签" :remote-method="remoteTagMethod" :loading="tagLoading" @change="handleInputConfirm">
            <el-option v-for="item in tagOptions" :key="item._id" :label="item.name" :value="item._id">
            </el-option>
          </el-select>
          <el-button v-else class="button-new-tag" size="small" @click="showInput" v-bind:disabled="this.dynamicTags.length > 4">+ 添加标签</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateAppTag">保 存</el-button>
        </span>
    </el-dialog>

    <el-dialog title="内容" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="70px" style='width: 650px; margin-left:30px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="temp.subtitle"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入内容" v-model="temp.brief">
          </el-input>
        </el-form-item>
        <el-form-item label="厂商(id)">
          <el-col :span="12">
            <el-input style="width: 100%" v-model="temp.vendor._id" @blur="checkVendor"></el-input>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="11">
            <el-select style="width: 100%;" v-model="temp.vendor._id" clearable filterable remote placeholder="请输入关键词" :remote-method="remoteMethod" :loading="vendorLoading">
              <el-option v-for="item in vendorOptions" :key="item._id" :label="item.name" :value="item._id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="temp.category._id" placeholder="请选择">
            <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包名">
          <el-input v-model="temp.packageName"></el-input>
        </el-form-item>
        <el-form-item label="评分" prop="score" :rules="[{pattern: /^(\d+(\.\d{1,2})?)?$/,message: '评分只能输入数值'}]">
          <el-input v-model.number="temp.score"></el-input>
        </el-form-item>
        <el-form-item label="权重值" prop="weight" :rules="[{pattern: /^(\d+(\.\d{1,2})?)?$/,message: '权重值只能输入数值'}]">
          <el-input v-model.number="temp.weight"></el-input>
        </el-form-item>
        <el-form-item label="下载量" prop="downloads" :rules="[{pattern: /^\d*$/,message: '下载量只能输入整数值'}]">
          <el-input v-model.number="temp.downloads"></el-input>
        </el-form-item>
        <el-form-item label="浏览量" prop="pageviews" :rules="[{pattern: /^\d*$/,message: '浏览量只能输入整数值'}]">
          <el-input v-model.number="temp.pageviews"></el-input>
        </el-form-item>
        <el-form-item label="启动次数" prop="opens" :rules="[{pattern: /^\d*$/,message: '启动次数只能输入整数值'}]">
          <el-input v-model.number="temp.opens"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

<script>
  import { fetch, getObjectById, insert, deleteById, update, cloud } from '@/api/jb'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox, Message } from 'element-ui'

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'app',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          include: 'versionInfo,category,vendor',
          where: {
            name: {
              $regex: '.*'
            },
            category: {
              __type: 'Pointer',
              className: 'Tag',
              _id: undefined
            },
            _id: {
              $sub: {
                where: {
                  tag: {
                    __type: 'Pointer',
                    className: 'Tag',
                    _id: undefined
                  }
                },
                searchClass: 'AppTag',
                searchKey: 'app'
              }
            },
            status: undefined
          },
          count: true,
          order: {
            updatedAt: -1
          }
        },
        whereQuery: {
          name: undefined,
          categoryId: undefined,
          tagId: undefined,
          status: undefined
        },
        listCategoryQuery: {
          skip: 0,
          limit: 100,
          keys: ['_id', 'name'],
          where: {
            type: 1,
            status: 1
          },
          order: {
            index: 1
          }
        },
        listTagQuery: {
          skip: 0,
          limit: 10,
          keys: ['_id', 'name'],
          where: {
            type: 2,
            status: 1
          },
          order: {
            weight: -1
          }
        },
        listAppTagQuery: {
          skip: 0,
          limit: 10,
          include: 'tag',
          where: {
            app: {
              __type: 'Pointer',
              className: 'App',
              _id: undefined
            }
          },
          order: {
            index: 1
          }
        },
        categoryOptions: [],
        vendorOptions: [],
        vendorLoading: false,
        listVendorQuery: {
          skip: 0,
          limit: 10,
          keys: ['_id', 'name'],
          where: {
            name: {
              $regex: '.*'
            }
          }
        },
        statusTypeOptions: [1, 2, 3],
        booleanOptions,
        temp: {
          _id: undefined,
          name: undefined,
          subtitle: undefined,
          brief: undefined,
          vendor: {
            _id: undefined,
            __type: 'Pointer',
            className: 'Vendor'
          },
          packageName: undefined,
          score: undefined,
          downloads: undefined,
          pageviews: undefined,
          opens: undefined,
          weight: undefined,
          category: {
            _id: undefined,
            __type: 'Pointer',
            className: 'Tag'
          },
          status: 2
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dynamicTags: [],
        inputVisible: false,
        editAppTagAppId: undefined,
        tagDialogVisible: false,
        tagOptions: [],
        tagLoading: false,
        tagEditLoading: true,
        inputValue: '',
        rules: {
          name: [{ required: true, message: '名称不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      statusTypeFilter(status) {
        const statusType = ['正常使用', '准备发布', '下架']
        return status > 0 ? statusType[status - 1] : ''
      },

      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
      fetch('Tag', this.listCategoryQuery).then(response => {
        this.categoryOptions = response.data.data.result
      })
    },
    methods: {
      getList() {
        this.listLoading = true
        if (this.whereQuery.categoryId) {
          this.listQuery.where.category = {
            __type: 'Pointer',
            className: 'Tag',
            _id: this.whereQuery.categoryId
          }
        } else {
          this.listQuery.where.category = undefined
        }
        if (this.whereQuery.tagId) {
          this.listQuery.where._id = {
            $sub: {
              where: {
                tag: {
                  __type: 'Pointer',
                  className: 'Tag',
                  _id: this.whereQuery.tagId
                }
              },
              searchClass: 'AppTag',
              searchKey: 'app'
            }
          }
        } else {
          this.listQuery.where._id = undefined
        }
        fetch('App', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleOrder(sort) {
        if (sort.prop) {
          const order = {}
          order[sort.prop] = sort.order === 'ascending' ? 1 : -1
          this.listQuery.order = order
        } else {
          this.listQuery.order = {
            updatedAt: -1
          }
        }
        this.getList()
      },
      handleFilter() {
        this.listQuery.skip = 0
        if (this.whereQuery.name) {
          this.listQuery.where.name = {
            $regex: '.*' + this.whereQuery.name + '.*'
          }
        } else {
          this.listQuery.where.name = undefined
        }
        if (this.whereQuery.status) {
          this.listQuery.where.status = this.whereQuery.status
        } else {
          this.listQuery.where.status = undefined
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          name: undefined,
          subtitle: undefined,
          brief: undefined,
          vendor: {
            _id: undefined,
            __type: 'Pointer',
            className: 'Vendor'
          },
          packageName: undefined,
          score: undefined,
          downloads: undefined,
          pageviews: undefined,
          opens: undefined,
          weight: undefined,
          category: {
            _id: undefined,
            __type: 'Pointer',
            className: 'Tag'
          },
          status: 2
        }
      },
      remoteTagMethod(keyword) {
        if (this.tagLoading) {
          return
        }
        if (keyword !== '') {
          this.tagLoading = true
          setTimeout(() => {
            this.tagLoading = false
            this.listTagQuery.where.name = {
              $regex: '.*' + keyword + '.*'
            }
            fetch('Tag', this.listTagQuery).then(response => {
              this.tagOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.tagOptions = []
        }
      },
      remoteMethod(keyword) {
        if (this.vendorLoading) {
          return
        }
        if (keyword !== '') {
          this.vendorLoading = true
          setTimeout(() => {
            this.vendorLoading = false
            this.listVendorQuery.where.name = {
              $regex: '.*' + keyword + '.*'
            }
            fetch('Vendor', this.listVendorQuery).then(response => {
              this.vendorOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.vendorOptions = []
        }
      },
      checkVendor() {
        if (this.temp.vendor._id) {
          var flag = false
          for (const item in this.vendorOptions) {
            if (this.vendorOptions[item]._id === this.temp.vendor._id) {
              flag = true
              break
            }
          }
          if (flag) {
            return
          }
          getObjectById('Vendor', this.temp.vendor._id).then(response => {
            this.vendorOptions.push(response.data.data.result)
          })
        }
      },
      handleCreate() {
        this.resetTemp()
        this.temp.status = 2
        this.vendorOptions = []
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.vendor._id) {
              tempData.vendor = undefined
            }
            if (!this.temp.category._id) {
              tempData.category = undefined
            }
            insert('App', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (!this.temp.vendor) {
          this.temp.vendor = {
            _id: undefined,
            __type: 'Pointer',
            className: 'Vendor'
          }
        } else {
          this.vendorOptions = [{
            '_id': row.vendor._id,
            'name': row.vendor.name
          }]
        }
        if (!this.temp.category) {
          this.temp.category = {
            _id: undefined,
            __type: 'Pointer',
            className: 'Tag'
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.vendor._id) {
              tempData.vendor = undefined
            }
            if (!this.temp.category._id) {
              tempData.category = undefined
            }

            update('App', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      },

      showInput() {
        if (this.dynamicTags.length > 4) {
          Message({
            message: '最多只能添加5个标签',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        this.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.focus()
        })
      },

      handleInputConfirm(val) {
        const inputValue = this.inputValue
        var flag = false
        for (const item in this.dynamicTags) {
          if (this.dynamicTags[item]._id === inputValue) {
            flag = true
            break
          }
        }
        if (!flag) {
          for (const item in this.tagOptions) {
            if (this.tagOptions[item]._id === inputValue) {
              this.dynamicTags.push({
                '_id': this.tagOptions[item]._id,
                'name': this.tagOptions[item].name
              })
            }
          }
        }
        this.tagOptions = []
        this.inputVisible = false
        this.inputValue = ''
      },
      handleStatus(row, value) {
        var message, title, confirmText
        if (value === 1) {
          // 发布
          message = '是否确认发布？发布后客户端可能会展示该应用！'
          title = '确认发布'
          confirmText = '发布'
        } else if (value === 3) {
          // 下架
          message = '是否确认下架该应用？下架后客户端将不再展示该应用！'
          title = '确认下架'
          confirmText = '下架'
        } else {
          return
        }
        MessageBox.confirm(message, title, {
          confirmButtonText: confirmText,
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const parmas = {
            'id': row._id,
            'status': value
          }
          cloud('updateAppStatus', parmas).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: confirmText + '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
            this.tagDialogVisible = false
          })
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('App', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      },
      openWindow(value) {
        window.open(value)
      },
      editAppTag(row) {
        this.tagEditLoading = true
        this.dynamicTags = []
        this.editAppTagAppId = row._id
        this.listAppTagQuery.where.app._id = row._id
        this.tagDialogVisible = true
        fetch('AppTag', this.listAppTagQuery).then(response => {
          const result = response.data.data.result
          for (const item in result) {
            this.dynamicTags.push({
              '_id': result[item].tag._id,
              'name': result[item].tag.name
            })
          }
          this.tagEditLoading = false
        })
      },
      updateAppTag() {
        var tags = ''
        for (const item in this.dynamicTags) {
          tags += this.dynamicTags[item]._id + ','
        }
        const parmas = {
          'appId': this.editAppTagAppId,
          'tags': tags
        }
        cloud('bindAppTag', parmas).then(response => {
          if (response.data.code === 0) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message,
              type: 'info',
              duration: 2000
            })
          }
          this.tagDialogVisible = false
        })
      }
    }
  }
</script>
<style scoped>

</style>
